/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rapidp2p.backend;

/**
 *
 * @author LF
 */
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {
    
    String tcpServerIP = null;
    //String saveName = null;
    String currentDirectory = System.getProperty("user.home") ;
    
    //System.out.println("Save directory is :" + currentDirectory);
        //File uploadDirectory = new File(currentDirectory + "\\share\\");
    TCPClient(String tcpServerIP){
        this.tcpServerIP = tcpServerIP;
        //this.saveName = saveName;
    }
    public void tcpClientInit(String saveName){
        byte[] aByte = new byte[1];
        int bytesRead;
        String saveName2 = saveName;
        Socket clientSocket = null;
        InputStream is = null;

        try {
            //clientSocket = new Socket("127.0.0.1", 3248);
            clientSocket = new Socket(tcpServerIP, 3248);//CHANGE IP 
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }
                
        
        
        //write file to hard drive somewhere
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream(saveName2);
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
    public static void main(String args[]) {
        String ipInput = null;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        try{
        ipInput = inFromUser.readLine();
        }catch (IOException io){
            System.out.println("IP input for TCPServer failed");
        }
        //TCPClient tcpc = new TCPClient(ipInput);
        //tcpc.tcpClientInit();
    }
}
